package com.captjack.micro.service.message.handler.impl;

import com.captjack.micro.common.entity.EmailMessageEntity;
import com.captjack.micro.service.message.handler.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * 发送邮件实现
 *
 * @author Capt Jack
 * @date 2018/3/29
 */
@Component
public class EmailServiceImpl implements EmailService {

    /**
     * 发送邮件工具
     */
    private final JavaMailSender javaMailSender;

    @Override
    public boolean sendEmail(EmailMessageEntity emailMessageEntity) throws Exception {
        try {
            // 收件人列表不能为空
            if (emailMessageEntity.getTo() == null || emailMessageEntity.getSubject() == null || emailMessageEntity.getText() == null) {
                throw new NullPointerException("email receivers、subject or content is null value, exit!");
            }
            // 获取邮件发送模版
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            // 发送辅助类
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            // 收件人集合
            mimeMessageHelper.setTo(emailMessageEntity.getTo());
            // 抄送人集合
            if (emailMessageEntity.getCc() != null && emailMessageEntity.getCc().length > 0) {
                // 收件人集合
                mimeMessageHelper.setCc(emailMessageEntity.getCc());
            }
            // 邮件主题
            mimeMessageHelper.setSubject(emailMessageEntity.getSubject());
            // 内容
            mimeMessageHelper.setText(emailMessageEntity.getText());
            // 附件
            mimeMessageHelper.setFrom(emailMessageEntity.getFrom());
            if (emailMessageEntity.getAttaches() != null) {
                for (File file : emailMessageEntity.getAttaches()) {
                    mimeMessageHelper.addAttachment(file.getName(), file);
                }
            }
            // 尝试发送
            javaMailSender.send(mimeMessage);
            return true;
        } catch (Exception e) {
            throw e;
        }
    }

    @Autowired
    public EmailServiceImpl(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

}
